# _*_ coding:utf-8 _*_
# @File  : common_image.py
# @Time  : 2021-12-09  09:38
# @Author: zizle

import datetime
import uuid
import time
import pathlib
from fastapi import APIRouter, UploadFile, Form
from configs import FILE_STORAGE, WEB_HOST
from status import r_status
image_api = APIRouter()


# 图片上传
@image_api.post('/upload/')
async def image_upload(file: UploadFile = Form(...)):
    # 使用uuid+时间戳的名称保存到服务器文件地址保存起来
    uuid_str = ''.join(str(uuid.uuid4()).split('-'))
    filename = str(int(time.time() * 1000)) + uuid_str + pathlib.Path(file.filename).suffix
    month = datetime.datetime.today().strftime('%Y%m')
    middle_folder = pathlib.Path('MEDIA/images/').joinpath(month)

    file_folder = pathlib.Path(FILE_STORAGE).joinpath(middle_folder)
    if not file_folder.exists():
        file_folder.mkdir(parents=True)
    filepath = file_folder.joinpath(filename)
    content = await file.read()  # 将文件保存到目标位置
    with open(filepath, "wb") as fp:
        fp.write(content)
    await file.close()
    # img_url = WEB_HOST + str(pathlib.Path(middle_folder).joinpath(filename)).replace('\\', '/')
    img_url = '/static/' + str(pathlib.Path(middle_folder).joinpath(filename)).replace('\\', '/')
    return {'code': r_status.CREATED_SUCCESS, 'message': '上传图片成功!', 'img_url': img_url}
